#!/usr/bin/env python
from GetCvPicture import PicGetter
import rospy
import cv2
import time
from std_srvs.srv import Trigger, TriggerResponse
from pyzbar.pyzbar import decode
import threading

class Qr_Detector:
    def __init__(self):
        pass

    def distinguish(self,image):
         # 解码二维码
        decoded_objects = decode(image)

        if len(decoded_objects) == 1:
            content = decoded_objects[0].data.decode('utf-8')
            
            print(f"内容: {content}")

            if content == "Vegetable":
                rospy.set_param("/buying_task","蔬菜")
                return "蔬菜"
            elif content == "Dessert":
                rospy.set_param("/buying_task","甜品")
                return "甜品"
            elif content == "Fruit":
                rospy.set_param("/buying_task","水果")
                return "水果"
        rospy.loginfo("未检测到有效二维码")
        return None

    # # 可选：可视化标记二维码
    # for obj in decoded_objects:
    #     cv2.rectangle(image, (obj.rect.left, obj.rect.top),
    #                   (obj.rect.left + obj.rect.width, obj.rect.top + obj.rect.height),
    #                   (0, 255, 0), 2)

    # cv2.imshow("test", image)
    # cv2.waitKey(1)

class QRService:
    def __init__(self):
        self.detector = Qr_Detector()
        self.service = None
        self.cap = PicGetter()

    
    def delayed_shutdown(self):
        time.sleep(2)  # 确保 response 被发出去
        rospy.signal_shutdown("任务已完成")

    def doRequest(self, req):
        count = 0
        while count < 15:
            img = self.cap.Get()
            if img is None:
                time.sleep(0.1)
                continue
                
            res = self.detector.distinguish(img)
            if res is None:
                count += 1
                time.sleep(0.1)
                continue
            else:
                rospy.loginfo("任务完成，准备关闭节点")
                threading.Thread(target=self.delayed_shutdown).start()
                return TriggerResponse(True, res)
        return TriggerResponse(False, "timeout")

    def start(self):
        self.cap.start()
        self.service = rospy.Service("QRDetectService", Trigger, self.doRequest)
        rospy.loginfo("QRDetect Service is ready")

if __name__ == '__main__':
    rospy.init_node("QRDetectServiceNode")

    service =QRService()

    service.start()

    rospy.spin()




